﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using BLL;

public partial class product_add : System.Web.UI.Page
{
    BLL.Business.BookBLL bookBLL = new BLL.Business.BookBLL();
    BLL.Business.UserBLL userBLL = new BLL.Business.UserBLL();
    Model.Book book = new Model.Book () ;
    // 初始化大类列表
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            BindBigType();
            if (!object.Equals(Request.QueryString["Book_Idint"], null)) // 此时是查看信息或是编辑
            {
                DataBindTable();
            }
            else                                                         // 此时是添加信息
            {
                this.Button1.Enabled = false;
            }
        }
    }
    // 绑定大类产品
    public void BindBigType()
    {
        try
        {
            DataSet ds = bookBLL.SelectBigType();
            if ((ds == null) ||
                (ds.Tables.Count == 0) ||
                (ds.Tables.Count == 1 && ds.Tables[0].Rows.Count == 0))
            {
                return;
            }
            else
            {
                bigType.Items.Clear();  // 清楚
                bigType.DataSource = ds;
                bigType.DataTextField = "BigType_Namestr";
                bigType.DataBind();
            }
        }
        catch (Exception ex)
        {
            Response.Write("<script>alert('" + ex.Message.ToString() + "')</script>");
        }
    }
    // 如果是修改数据,将信息绑定到Table
    public void DataBindTable()
    {
        try
        {
            if (!object.Equals(Request.QueryString["Book_Idint"], null))
            {
                int bookId = Int32.Parse(Request.QueryString["Book_Idint"].ToString());
                DataSet ds = bookBLL.SelectByBookId(bookId);

                if ((ds == null) ||
                 (ds.Tables.Count == 0) ||
                 (ds.Tables.Count == 1 && ds.Tables[0].Rows.Count == 0))
                {
                    return;
                }
                else
                {
                    this.bookName.Text = ds.Tables[0].Rows[0]["Book_Namestr"].ToString();// 书名
                    //------- 绑定大类
                    for (int i = 0; i < this.bigType.Items.Count; i++)                   // 绑定大类
                    {
                        if (this.bigType.Items[i].Text.ToString() == ds.Tables[0].Rows[0]["BigType_Namestr"].ToString())
                            this.bigType.Items[i].Selected = true; ;
                    }
                    String bigTypeStr = this.bigType.SelectedItem.Text.ToString();
                    //------- 绑定小类
                    DataSet ds2 = bookBLL.SelectSmallType(bigTypeStr);
                    if ((ds2 == null) ||
                        (ds2.Tables.Count == 0) ||
                        (ds2.Tables.Count == 1 && ds2.Tables[0].Rows.Count == 0))
                    {
                        smallType.Items.Clear();
                        return;
                    }
                    else
                    {
                        smallType.Items.Clear();
                        smallType.DataSource = ds2;
                        smallType.DataTextField = "SmallType_Namestr";
                        smallType.DataBind();
                    }
                    for (int i = 0; i < this.smallType.Items.Count; i++)
                    {
                        if (this.smallType.Items[i].Text.ToString() == ds.Tables[0].Rows[0]["SmallType_Namestr"].ToString())
                        {
                            this.smallType.Items[i].Selected = true;
                        }
                    }
                    //----- 绑定小类 END


                    this.smallType.SelectedItem.Text = ds.Tables[0].Rows[0]["SmallType_Namestr"].ToString();
                    this.author.Text = ds.Tables[0].Rows[0]["Book_Authorstr"].ToString();
                    this.publisher.Text = ds.Tables[0].Rows[0]["Book_Publisherstr"].ToString();
                    this.price.Text = ds.Tables[0].Rows[0]["Book_Priceflo"].ToString();
                    this.discount.Text = ds.Tables[0].Rows[0]["Book_Discountflo"].ToString();
                    this.UpfileName.Text = ds.Tables[0].Rows[0]["Book_Coverstr"].ToString();
                    this.detail.Text = ds.Tables[0].Rows[0]["Book_Descriptiontext"].ToString();
                    this.count.Text = ds.Tables[0].Rows[0]["Book_Countint"].ToString();
                    this.importCount.Text = ds.Tables[0].Rows[0]["Book_ImportCountint"].ToString();

                    bool IsChecked = bool.Parse(ds.Tables[0].Rows[0]["Book_Statusbit"].ToString());
                    if (IsChecked == true)
                        this.onShow.Checked = true;
                    else
                        this.onHide.Checked = true;

                    this.insert.Enabled = false;       // 不能添加
                }
            }
        }
        catch (Exception ex)
        {
            Response.Write("<script>alert('" + ex.Message.ToString() + "')</script>");
        }
    }
    // 根据产品大类选择小类
    protected void bigType_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            String bigType = this.bigType.SelectedItem.Text.ToString();
            DataSet ds = bookBLL.SelectSmallType(bigType);
            if ((ds == null) ||
                (ds.Tables.Count == 0) ||
                (ds.Tables.Count == 1 && ds.Tables[0].Rows.Count == 0))
            {
                smallType.Items.Clear();
                return;
            }
            else
            {
                smallType.Items.Clear();
                smallType.DataSource = ds;
                smallType.DataTextField = "SmallType_Namestr";
                smallType.DataBind();
            }
        }
        catch (Exception ex)
        {
            Response.Write("<script>alert('" + ex.Message.ToString() + "')</script>");
        }
    }
    // 开始上传文件
    protected void Button2_Click(object sender, EventArgs e)
    {
        if (FileUpLoad1.HasFile)
        {
            //判断文件是否小于10Mb  
            if (FileUpLoad1.PostedFile.ContentLength < 10485760)
            {
                try
                {
                    if (!File.Exists(Server.MapPath("~/BackManage/UploadPicture/")  //  如果不存在同名的就上传
                        + FileUpLoad1.FileName))
                    {
                        //上传文件并指定上传目录的路径  
                        String NewFileName = GetRandomFileName(FileUpLoad1.FileName);
                        FileUpLoad1.PostedFile.SaveAs(Server.MapPath("~/BackManage/UploadPicture/")
                            + NewFileName);

                        /*注意->这里为什么不是:FileUpLoad1.PostedFile.FileName 
                        * 而是:FileUpLoad1.FileName? 
                        * 前者是获得客户端完整限定(客户端完整路径)名称 
                        * 后者FileUpLoad1.FileName只获得文件名. 
                        */
                        this.UpfileName.Text = NewFileName;
                        lblMessage.Text = "上传成功!";
                    }
                }
                catch (Exception ex)
                {
                    lblMessage.Text = "出现异常,无法上传!"+"  "+ex.Message.ToString();
                }
            }
            else
            {
                lblMessage.Text = "上传文件不能大于10MB!";
            }
        }
        else
        {
            lblMessage.Text = "尚未选择文件!";
        }  
    }
    // 确定添加(添加到二手书)
    protected void Unnamed1_Click(object sender, EventArgs e)
    {
        try
        {
            String UserName = Session["UserName"].ToString();
            int UserId = Int32.Parse((userBLL.SelectByName(UserName)).Tables[0].Rows[0]["User_Idint"].ToString());

            String Book_Namestr = this.bookName.Text.ToString();
            String SmallType_Namestr = this.smallType.SelectedItem.Text.ToString();
            String Book_Authorstr = this.author.Text.ToString();
            String Book_Publisherstr = this.publisher.Text.ToString();
            float Book_Priceflo = float.Parse(this.price.Text.ToString());
            float Book_Discountflo = float.Parse(this.discount.Text.ToString());

            String Book_Coverstr = this.UpfileName.Text.Trim().ToString();

            String Book_Descriptiontext = this.detail.Text.ToString();
            int Book_Countint = Int32.Parse(this.count.Text.ToString());
            int Book_Statusbit = ((this.onShow.Checked == true) ? 1 : 0);  // 在售1；下架0
            DateTime Book_ImportTimedate = DateTime.Now;
            int Book_ImportCountint = Int32.Parse(this.importCount.Text.ToString());

            book.Book_Authorstr = Book_Authorstr;
            book.Book_Countint = Book_Countint;
            book.Book_Coverstr = Book_Coverstr;
            book.Book_Descriptiontext = Book_Descriptiontext;
            book.Book_Discountflo = Book_Discountflo;
            book.Book_ImportTimedate = Book_ImportTimedate;
            book.Book_Namestr = Book_Namestr;
            book.Book_Priceflo = Book_Priceflo;
            book.Book_Publisherstr = Book_Publisherstr;
            book.Book_Statusbit = Book_Statusbit;
            book.SmallType_Namestr = SmallType_Namestr;
            book.Book_ImportCountint = Book_ImportCountint;

            if (bookBLL.InsertSecondBook(book, UserId))
            {
                Response.Write("<script>alert('添加成功')</script>");
            }
            else
            {
                Response.Write("<script>alert('添加失败，请检查！')</script>");
            }
        }
        catch
        {
            Response.Write("<script>alert('添加失败，请检查！')</script>");
        }
    }
    // 信息更新
    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            String Book_Namestr = this.bookName.Text.ToString();
            String SmallType_Namestr = this.smallType.SelectedItem.Text.ToString();
            String Book_Authorstr = this.author.Text.ToString();
            String Book_Publisherstr = this.publisher.Text.ToString();
            float Book_Priceflo = float.Parse(this.price.Text.ToString());
            float Book_Discountflo = float.Parse(this.discount.Text.ToString());

            String Book_Coverstr =  UpfileName.Text.Trim().ToString();

            String Book_Descriptiontext = this.detail.Text.ToString();
            int Book_Countint = Int32.Parse(this.count.Text.ToString());
            int Book_Statusbit = ((this.onShow.Checked == true) ? 1 : 0);  // 在售1；下架0
            DateTime Book_ImportTimedate = DateTime.Now;
            int Book_ImportCountint = Int32.Parse(this.importCount.Text.ToString());

            book.Book_Idint = Int32.Parse(Request.QueryString["Book_Idint"]);
            book.Book_Authorstr = Book_Authorstr;
            book.Book_Countint = Book_Countint;
            book.Book_Coverstr = Book_Coverstr;
            book.Book_Descriptiontext = Book_Descriptiontext;
            book.Book_Discountflo = Book_Discountflo;
            book.Book_ImportTimedate = Book_ImportTimedate;
            book.Book_Namestr = Book_Namestr;
            book.Book_Priceflo = Book_Priceflo;
            book.Book_Publisherstr = Book_Publisherstr;
            book.Book_Statusbit = Book_Statusbit;
            book.SmallType_Namestr = SmallType_Namestr;
            book.Book_ImportCountint = Book_ImportCountint;

            if (bookBLL.UpdateBook(book))
            {
               Response.Write("<script>alert('修改成功')</script>");
            }
            else
            {
                Response.Write("<script>alert('修改失败，请检查！')</script>");
            }
        }
        catch(Exception ex)
        {
            Response.Write("<script>alert('"+ex.Message.ToString()+"')</script>");
        }
    }
    // 获得文件名
    public String GetFileName(String file)
    {
        int len = file.LastIndexOf("\\");
        return file.Substring(len+2, file.Length - (len + 2));
    }
    // 生成随机文件名
    public String GetRandomFileName(String OldFileName)
    {
        String NewFileName = "";  // 新文件名
        Random ran = new Random();// 随机数
        String Extension = "";    // 后缀
        Extension = OldFileName.Substring(OldFileName.LastIndexOf(".")+1, OldFileName.Length - OldFileName.LastIndexOf(".")-1);
        NewFileName += ran.Next(1, 100).ToString();
        NewFileName += DateTime.Now.Year.ToString();
        NewFileName += DateTime.Now.Month.ToString();
        NewFileName += DateTime.Now.Day.ToString();
        NewFileName += DateTime.Now.Hour.ToString();
        NewFileName += DateTime.Now.Minute.ToString();
        NewFileName += DateTime.Now.Second.ToString();
        NewFileName += DateTime.Now.Millisecond.ToString();
        NewFileName += "."+ Extension;
        return NewFileName;
    }
}
